package com.fulihui.wgj.consumer.communication.event;

import com.fulihui.common.enums.EventTypeEnum;
import com.fulihui.common.util.SevenRemainingUtil;
import com.fulihui.common.util.TenMinutesMsgUtil;
import com.fulihui.wgj.consumer.service.SubUserDatilService;
import com.fulihui.wgj.consumer.service.UserService;
import com.fulihui.wgj.facade.msg.EventMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * @author: LiuJie
 * @version: 2018/7/4 13:43
 * @description:
 */
@Component
@Slf4j
public class UnsubscribeEventProcessor implements EventMsgProcessor {

    @Autowired
    SubUserDatilService subUserDatilService;
    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    UserService userService;
    @Autowired
    TenMinutesMsgUtil tenMinutesMsgUtil;
    @Autowired
    SevenRemainingUtil sevenRemainingUtil;

    @Override
    public void process(EventMsg message) {
        String appId = message.getAppId();
        String openId = message.getFromUserName();
        if (StringUtils.isBlank(appId) || StringUtils.isBlank(openId)) {
            log.error("取关事件终止，用户appid 或 openid 为空 appid = {}，openid = {}",appId,openId);
            return;
        }
        // 删除用户
        userService.delUser(appId,openId);

        //  七日留存-记录取关数
        sevenRemainingUtil.recordUnsubscribe(appId,sevenRemainingUtil.get(openId),openId);
        // 七日留存-删除redis缓存的关注时间，针对有效期内取关用户
        sevenRemainingUtil.del(openId);

        // 十分钟拉活删除-针对十分钟之内就取关的用户
        tenMinutesMsgUtil.rmSubscribe(appId,openId);

        // wx_sub_user_datil 标记为取关
        threadPoolTaskExecutor.execute(()->{
            subUserDatilService.recordUnSubscribe(appId,openId);
        });

    }

    @Override
    public String getEvent() {
        return EventTypeEnum.unsubscribe.getCode();
    }
}
